<template>
    <div class="margin-bottom-50">
        <div class="container_box">
            <el-button type="primary"
                       @click="back">返回</el-button>
            <div class="steps u-flex u-row-center">
                <div class="step step_r"
                     v-for="(item,index) in stepList"
                     :key="index"
                     @click="stepIndex = index+1"
                     :class="{'active': stepIndex == (index+1)}">
                    <div style="position:absolute;right:-42px;height:40px;width:80px;overflow:hidden;">
                        <div class="rotateBox"></div>
                    </div>
                    <div class="step_b">
                        {{ item.text }}
                    </div>
                </div>
            </div>
        </div>
        <el-upload style="display:none"
                   action=""
                   :http-request="uploadHttp"
                   :on-progress="zzUpload"
                   list-type="picture"
                   :multiple="false"
                   name="files">
            <el-button size="small"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
        </el-upload>
        <div class="padding_box">
            <!-- <div class="container_box">
                <div class="container_title">课程类型</div>
                <div class="product-type u-flex u-row-around u-col-center">
                    <div>平台课程</div>
                    <img class="product-type-img"
                         :src="editProduct.pic"
                         alt="">
                    <img class="product-select"
                         src="@/assets/img/product_select.png"
                         alt="">
                </div>
            </div> -->
            <div v-show="stepIndex == 1"
                 class="container_box">
                <div class="container_title">基本信息</div>
                <el-form ref="form"
                         :model="editProduct"
                         :rules="rules"
                         label-width="80px">
                    <el-form-item label="封面图片"
                                  prop="pic">
                        <el-upload class="avatar-uploader"
                                   action=""
                                   :http-request="uploadHttp2"
                                   name="files"
                                   accept=".png,.jpg,.jpeg"
                                   :on-progress="zzUpload">
                            <img v-if="editProduct.pic"
                                 :src="editProduct.pic"
                                 class="avatar">
                            <i v-else
                               class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="轮播图片"
                                  prop="carouselimg">

                        <el-upload :http-request="uploadHttp3"
                                   action=""
                                   list-type="picture-card"
                                   :on-preview="handlePictureCardPreview"
                                   :on-remove="handleRemove"
                                   accept=".png,.jpg,.jpeg,.mp4"
                                   name="files"
                                   :limit="9"
                                   :file-list="carouselimg">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="carouselVisible">
                            <img width="100%"
                                 :src="largeImg"
                                 alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item label="主图视频">
                        <el-upload class="video-uploader"
                                   :http-request="uploadHttpVideo"
                                   action=""
                                   :on-preview="handleVideoPreview"
                                   :on-progress="uploadVideoProcess"
                                   :on-success="handleUploadVideoSuccess"
                                   name="files"
                                   :limit="1">
                            <video class="video"
                                   width="100%"
                                   v-if="editProduct.mainVideo && !videoFlag"
                                   controls
                                   :src="editProduct.mainVideo"></video>
                            <i v-else-if="!editProduct.mainVideo && !videoFlag"
                               class="el-icon-plus video-uploader-icon"></i>
                            <el-progress v-if="videoFlag"
                                         type="circle"
                                         :percentage="videoUploadPercent"
                                         style="margin-top:30px;"></el-progress>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="课程名称"
                                  prop="name"
                                  style="width:40%">
                        <el-input v-model="editProduct.name"></el-input>
                    </el-form-item>
                    <el-form-item label="是否上架">
                        <el-radio-group v-model="editProduct.online">
                            <el-radio :label="true">上架</el-radio>
                            <el-radio :label="false">下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <!-- <el-form-item style="width:40%"
                                  prop="originalPrice"
                                  label="市场价 (元)">
                        <el-input onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                                  v-model="editProduct.originalPrice"
                                  placeholder="请输入市场价格"></el-input>
                    </el-form-item>
                    <el-form-item style="width:40%"
                                  label="成本价 (元)">
                        <el-input onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                                  v-model="editProduct.price"
                                  placeholder="请输入成本价"></el-input>
                    </el-form-item> -->
                    <el-form-item style="width:40%"
                                  prop="priceDouble"
                                  onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                                  label="销售价  (元)">
                        <el-input-number placeholder="请输入在价格"
                                         :min="0"
                                         :controls="false"
                                         :precision="2"
                                         v-model.trim="editProduct.priceDouble"></el-input-number>
                    </el-form-item>
                    <!-- <el-form-item style="width:40%"
                                  prop="otherSale"
                                  label="其它销量"
                                  placeholder="请输入销量(整数)">
                        <el-input v-model="editProduct.otherSale"
                                  onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
                    </el-form-item> -->
                    <!-- <el-form-item label="分享语"
                                  style="width:40%">
                        <el-input v-model="editProduct.shareTitle"></el-input>
                    </el-form-item> -->

                    <!-- <el-form-item style="width:40%"
                                  label="单位">
                        <el-input v-model="editProduct.unit"
                                  placeholder="请输入单位"></el-input>
                    </el-form-item> -->
                    <el-form-item label="课程分类">
                        <el-cascader ref="myCascader"
                                     filterable
                                     :show-all-levels="false"
                                     separator=">"
                                     :placeholder="productCategoryName"
                                     v-model="productCategory"
                                     @change="handleChange"
                                     :options="productCategoryList"
                                     :props="{ expandTrigger: 'hover', checkStrictly: false, value:'id',label:'name',children:'children', }">
                        </el-cascader>
                        <!-- <el-select v-model="productCategory"
                                   @change="handleChange"
                                   ref="mySelect"
                                   placeholder="请选择">
                            <el-option v-for="(item,index) in productCategoryList"
                                       :key="item.id"
                                       :label="item.name"
                                       :value="item.id"></el-option>
                        </el-select> -->
                    </el-form-item>
                    <!-- <el-form-item label="详情内容">
                        <quill-editor ref="QuillEditor"
                                      v-model="editProduct.detailTabs[0].tabDetails"
                                      :options="editorOption"></quill-editor>
                    </el-form-item> -->
                    <div v-for="(item,index) in editProduct.detailTabs"
                         :key="index">
                        <el-form-item label="详情标题"
                                      style="width:40%">
                            <el-input v-model="item.title"></el-input>
                        </el-form-item>
                        <el-form-item label="详情内容"
                                      @click="currentEditorIndex = index">
                            <quill-editor ref="QuillEditor"
                                          :id="index"
                                          @change="currentEditorIndex = index"
                                          @focus="currentEditorIndex = index"
                                          v-model="item.tabDetails"
                                          :options="editorOption"></quill-editor>
                        </el-form-item>
                    </div>
                    <el-form-item label="商品内容">
                        <el-button @click="zeng"
                                   type="success">增加内容</el-button>
                        <el-button @click="jian"
                                   type="success">减少内容</el-button>
                    </el-form-item>
                    <el-form-item style="width:100%"
                                  label="购买须知">
                        <el-input type="textarea"
                                  :rows="4"
                                  placeholder="购买须知"
                                  v-model="editProduct.note">
                        </el-input>
                    </el-form-item>
                    <!-- <el-form-item style="width:100%"
                                  label="课程描述"
                                  prop="description">
                        <el-input type="textarea"
                                  :rows="4"
                                  placeholder="请输入课程描述"
                                  v-model="editProduct.description">
                        </el-input>
                    </el-form-item> -->
                </el-form>
            </div>

            <div v-show="stepIndex == 2"
                 class="container_box">
                <div class="container_title">价格库存</div>
                <el-form ref="form"
                         :model="editProduct"
                         label-width="80px">
                    <el-form-item label="规格类型"
                                  prop="specifications">
                        <el-radio-group v-model="specifications">
                            <!-- <el-radio label="single">统一规格</el-radio> -->
                            <el-radio label="many">多规格</el-radio>
                        </el-radio-group>
                        <div v-if="specifications == 'many'">
                            <div class="specifications-box">
                                <div v-for="(item,index) in specificationsList"
                                     :key="index"
                                     class="specifications-item">
                                    <el-form ref="form"
                                             :rules="specificationsRules"
                                             :model="item"
                                             label-width="80px">
                                        <div class="u-flex u-flex-row">
                                            <el-form-item label="规格名"
                                                          prop="name"
                                                          style="width:40%">
                                                <el-input v-model="item.name"
                                                          placeholder="请输入规格名"></el-input>
                                            </el-form-item>
                                            <el-form-item label="规格单位"
                                                          style="width:40%">
                                                <el-input v-model="item.unit"
                                                          placeholder="请输入规格单位"></el-input>
                                            </el-form-item>
                                        </div>
                                        <el-form-item label="规格值"
                                                      prop="values">
                                            <div class="specifications-value u-flex u-flex-wrap">
                                                <div class="input-box"
                                                     v-for="(item1, index1) in item.values"
                                                     :key="index1">
                                                    <el-input placeholder="请输入规格值"
                                                              v-model="item.values[index1]">
                                                    </el-input>
                                                    <i class="el-icon-error"
                                                       @click="deleteSpecificationsValue(item.values,index1)"></i>
                                                </div>
                                                <el-button class="add_btn"
                                                           size="mini"
                                                           type="primary"
                                                           @click="addSpecificationsValue(item.values)">添加规格值</el-button>
                                            </div>
                                        </el-form-item>
                                    </el-form>
                                    <i class="el-icon-error"
                                       @click="deleteSpecificationsItem(item,index)"></i>
                                </div>
                            </div>
                            <p class="tips">修改规格后，需点击保存课程才可修改SKU</p>
                            <div style="float:right;">

                                <el-button size="mini"
                                           type="primary"
                                           @click="addSpecifications()">添加规格</el-button>
                                <el-button size="mini"
                                           type="success"
                                           @click="saveSpecifications()">保存课程规格</el-button>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="课程SKU"
                                  prop="specifications">
                        <div class="sku-box">
                            <div style="margin-bottom:25px;">
                                <div v-for="(item,index) in skuList"
                                     :key="index"
                                     class="specifications-value-box">
                                    <div class="specifications-title">规格名：{{ item.name }}</div>
                                    <div class="u-flex u-flex-wrap">
                                        <div class="specifications-value"
                                             v-for="(item1,index1) in item.values"
                                             :key="index1"
                                             :class="{ 'active': selectArr[index] == index1 }"
                                             @click="changeSpecification(index, index1)">
                                            {{ item1 }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <el-table v-if="skuList.length == selectArr.length"
                                      v-loading="loading"
                                      :data="[currentSkuData]"
                                      border
                                      class="my_table"
                                      ref="multipleTable"
                                      header-cell-class-name="table-header">

                                <el-table-column label="所选规格"
                                                 align="center">
                                    <template slot-scope="scope"
                                              v-if="selectArr.length > 0">
                                        <p v-for="(item1,index1) in skuList"
                                           :key="index1">{{ item1.values[selectArr[index1]]}} {{  (skuList.length>1 && index1 < skuList.length-1) ? '+' : ''  }}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="priceDouble"
                                                 label="价格(元)"
                                                 align="center">
                                    <template slot-scope="scope">
                                        <el-input-number placeholder="请输入在价格"
                                                         :min="0"
                                                         :controls="false"
                                                         :precision="2"
                                                         v-model.trim="scope.row.priceDouble"></el-input-number>
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column prop="originalPrice"
                                                 label="市场价(分)"
                                                 align="center">
                                    <template slot-scope="scope">
                                        <el-input placeholder="请输入市场价"
                                                  oninput="value=value.replace(/[^0-9.]/g,'')"
                                                  v-model="scope.row.originalPrice">
                                        </el-input>
                                    </template>
                                </el-table-column> -->
                                <!-- <el-table-column prop="stock"
                                                 label="库存(个)"
                                                 align="center">
                                    <template slot-scope="scope">
                                        <el-input placeholder="请输入库存"
                                                  oninput="value=value.replace(/[^0-9.]/g,'')"
                                                  v-model="scope.row.stock">
                                        </el-input>
                                    </template>
                                </el-table-column> -->
                                <el-table-column prop=""
                                                 label="课程图"
                                                 align="center">
                                    <template slot-scope="scope">
                                        <el-upload class="avatar-uploader"
                                                   :http-request="({file}) => uploadHttp4(file, scope.row)"
                                                   action=""
                                                   :limit="9"
                                                   name="files"
                                                   accept=".png,.jpg,.jpeg"
                                                   :on-progress="zzUpload">
                                            <img v-if="scope.row.pic"
                                                 :src="scope.row.pic"
                                                 class="avatar">
                                            <i v-else
                                               class="el-icon-plus avatar-uploader-icon"></i>
                                        </el-upload>
                                    </template>
                                </el-table-column>
                                <el-table-column prop=""
                                                 label="上架状态"
                                                 align="center">
                                    <template slot-scope="scope">
                                        <el-switch class="my-switchStyle"
                                                   v-model="scope.row.online"
                                                   :active-value="true"
                                                   :inactive-value="false"
                                                   active-color="#1B93F8"
                                                   active-text="上架"
                                                   inactive-color="#999999"
                                                   inactive-text="下架">
                                        </el-switch>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div style="float:right;margin-top:20px;">
                                <el-button size="mini"
                                           type="success"
                                           @click="saveCurrentSku()">保存当前选中SKU</el-button>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item v-if="specifications == 'many' "
                                  label="课程SKU列表">
                        <el-table :data="productSkuList"
                                  stripe
                                  border
                                  class="my_table"
                                  ref="multipleTable"
                                  header-cell-class-name="table-header">
                            <el-table-column prop=""
                                             label="课程图"
                                             align="center">
                                <template slot-scope="scope">
                                    <el-image class="avatar"
                                              :src="scope.row.pic"
                                              :preview-src-list="[scope.row.pic]">
                                    </el-image>
                                </template>
                            </el-table-column>
                            <el-table-column label="所选规格"
                                             align="center">
                                <template slot-scope="scope"
                                          v-if="scope.row.spDataList">
                                    <p v-for="(item1,index1) in scope.row.spDataList"
                                       :key="index1"> {{ item1.value }} {{  (scope.row.spDataList.length>1 && index1 < scope.row.spDataList.length-1) ? '+' : ''  }}</p>
                                </template>
                            </el-table-column>
                            <el-table-column prop="priceDouble"
                                             label="在售价(元)"
                                             align="center">
                            </el-table-column>
                            <el-table-column prop=""
                                             label="上架状态"
                                             align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.online ?'上架':'下架' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作"
                                             width="180"
                                             align="center">
                                <template slot-scope="scope">
                                    <el-button size="mini"
                                               type="warning"
                                               @click="deleteUser(scope.$index,scope.row.id)">删除</el-button>

                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-form>
            </div>
            <div class="container_box footer_box">
                <el-button @click="back">取 消</el-button>
                <el-button v-if="stepIndex > 1"
                           type="success"
                           @click="previousStep">上一步</el-button>
                <el-button v-if="stepIndex != 2"
                           type="success"
                           @click="nextStep">下一步</el-button>
                <el-button v-if="stepIndex > 1"
                           @click="saveEdit"
                           type="primary">完成</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import axios from '@/utils/axios.js';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';
import VueCropper from 'vue-cropperjs';
import { Loading } from 'element-ui';

// 工具栏配置
const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],
    [{ 'header': 1 }, { 'header': 2 }],               // custom button values
    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
    [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
    [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
    [{ 'direction': 'rtl' }],                         // text direction

    [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

    [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
    [{ 'font': [] }],
    [{ 'align': [] }],
    ['link', 'image', 'video'],
    ['clean']                                         // remove formatting button
]

export default {
    Uname: 'baseform',
    name: 'editor',
    data: function () {
        return {
            imgUrl: 'https://songsujiazhang.oss-cn-shenzhen.aliyuncs.com/2021/07/20/4f0af133-0c06-429b-93c9-ab4c68a6273f.jpg',
            uploadActionUrl: this.$urls + "api-file/files-anon?isAsync=false&access_token=" + sessionStorage.getItem('ms_token'),
            carouselVisible: false,
            largeImg: '',
            // 步骤条
            stepList: [
                { text: '1、编辑基本信息' }, { text: '2、编辑价格库存' },
                // { text: '3、预览效果' },
            ],
            // 步骤index
            stepIndex: 1,
            // 当前编辑对象数据
            editProduct: {

                id: "",
                pic: '',//图片
                mainVideo: '',
                priceDouble: 0,
                salePrice: '9999',//销售价
                originalPrice: '9999',//市场价
                online: true,//是否上架
                albumPics: '',//轮播图
                detailTabs: [{ tabDetails: '', title: '' }],
                categoryId: "",//商品分类id
                name: '',//名称
                price: '9999',//原价
                type: 0,//类型
                categoryName: "",
                skuList: [],
                note: '',
                sort: 0,
                verifyStatus: true,
                keywords: '',
                unit: '元'
            },
            // 轮播图List
            carouselimg: [],
            // 课程分类回显idList
            productCategory: '',
            productCategoryName: '',
            // 课程分类
            productCategoryList: [],
            // 富文本编辑器当前索引
            currentEditorIndex: '',
            // 富文本编辑器参数
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions,  // 工具栏
                        handlers: {
                            'image': function (value) {
                                if (value) {
                                    document.querySelector('.el-upload').click()
                                    // this.onSubmit()
                                    // alert('自定义图片',value)
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                }
            },
            loading: false,
            // 上传加载遮罩
            loaddingTip: {
                text: "正在上传,请稍等",
                background: "rgba(0, 0, 0, 0.7)"
            },
            // 区分单/多规格
            specifications: 'many',
            // 表单rules
            rules: {
                pic: [{ required: true, message: '请选择封面图', trigger: 'blur' }],
                carouselimg: [{ required: true, message: '请选择轮播图照片', trigger: 'blur' }],
                name: [{ required: true, message: '请输入课程名', trigger: 'blur' }],
                title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
                // description: [{ required: true, message: '请输入课程描述', trigger: 'blur' }],
                keywords: [{ required: true, message: '请输入关键字', trigger: 'blur' }],
                // originalPrice: [{ required: true, message: '请输入市场价', trigger: 'blur' }],
                priceDouble: [{ required: true, message: '请输入销售价', trigger: 'blur' }],
                otherSale: [{ required: true, message: '请输入其他销量', trigger: 'blur' }],
            },
            // 规格表单rules
            specificationsRules: {
                name: [{ required: true, message: '请输入规格名', trigger: 'blur' }],
                values: [{ required: true, message: '请输入规格值', trigger: 'blur' }],
            },
            // 当前选中索引组合indexes的SKU数据
            currentSkuData: {
                commission: false,
                online: true,
                speciaId: [],
                originalPrice: "",
                pic: "",
                price: "",
                productId: this.$route.query.id || localStorage.getItem('productId'),
                stock: "999",
                sale: 1,
                // type: 0,
                // verifyStatus: true
            },
            // 当前选中的索引组合
            selectArr: [],
            currentIndexes: '',
            skuList: [],
            carouselimg: [],
            zifu: '',
            // 课程SKU列表
            productSkuList: [],
            // 课程规格列表
            specificationsList: [
                { name: "", unit: '', values: [''] }
            ],         // 规格值列表
            input: '',
            // 区分有无课程视频
            videoFlag: false,
            videoUploadPercent: 0,
            mainVideoVisible: false,
        };
    },
    components: {
        quillEditor,
        VueCropper,
    },
    activated() {

    },
    watch: {
        selectArr: {
            handler(newVal, oldVal) {
                let key = newVal.join('-')
                let currentSkuData = this.productSkuList.find(ele => ele.speciaId == key)
                if (!currentSkuData) {
                    this.currentSkuData = {
                        priceDouble: '',
                        pic: '',
                        giveNum: 0,
                        commission: false,
                        online: true,
                        speciaId: [],
                        originalPrice: "",
                        price: "",
                        productId: this.$route.query.id || localStorage.getItem('productId'),
                        stock: "999",
                        sale: 1,
                        // type: 0,
                        // verifyStatus: true
                    }
                    // this.initSkuData(key)
                } else {
                    // 已有这个sku
                    this.currentSkuData = currentSkuData
                }
            },
            deep: true
        }
    },
    created() {
        if (this.currentSkuData.productId) {
            this.getData()
            // this.getSku()
        }
        this.getProductCategory()
    },
    destroyed() {
        // console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>-----------------')
        // window.removeEventListener("keydown", this.fecthTip(e))
    },
    methods: {
        /**
     * @param {string} value - 输入的值
     * @param {string} name - 匹配的对象属性 [mkPrice | slPrice]
     */
        limitInput(value, name) {
            this.form[name] =
                ("" + value) // 第一步：转成字符串
                    .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
                    .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
                    .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
                    .match(/^\d*(\.?\d{0,2})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
        },
        // fecthTip(e) {
        //     let _this = this
        //     if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82)) {
        //         e.preventDefault();
        //         _this.$confirm('刷新页面信息会丢失,是否要刷新？', '提示', {
        //             type: 'warning'
        //         }).then(() => {
        //             _this.$router.go(-1)
        //             return false
        //         })
        //     }
        // },
        back() {
            this.$confirm('您即将离开该页面，页面信息会丢失是否确认离开？', '提示', {
                type: 'warning'
            }).then(() => {
                this.$router.go(-1)
            })
        },
        // 获取课程分类
        getProductCategory() {
            axios({
                url: "admin/productCategory/tree",
                method: "post",
            }).then(result => {
                const { data } = result;
                data.forEach(ele => {
                    this.removeChildren(ele)
                });
                this.productCategoryList = data || [];

            })
        },
        removeChildren(node) {
            if (!node.children || !node.children.length) {
                delete node.children
            }
            if (node.children && node.children.length) {
                for (let i = 0; i < node.children.length; i++) {
                    this.removeChildren(node.children[i])
                }
            }
            return true
        },
        // 获取课程数据
        getData() {
            axios({
                url: "/admin/product/getById",
                method: "post",
                data: { id: this.currentSkuData.productId },
            }).then(result => {
                if (result.code == 0) {
                    const { data } = result;
                    this.editProduct = data;
                    let albumArr = data.albumPics.split(',');
                    let simg = [];

                    for (var i = 0; i < albumArr.length; i++) {
                        simg.push({ url: albumArr[i] })
                    }
                    // 产品分类
                    this.productCategory = data.categoryId
                    this.productCategoryName = data.categoryName
                    // 轮播图
                    this.carouselimg = simg
                    // this.zifu = simg
                    // 规格
                    let speciaId = []
                    if (data.productSpecialVos) {
                        this.specificationsList = data.productSpecialVos
                        this.skuList = JSON.parse(JSON.stringify(data.productSpecialVos))
                        this.skuList.forEach(ele => {
                            // 初始化默认选中第一个规格值
                            speciaId.push(0)
                        });
                        this.selectArr = speciaId

                    }
                    this.productSkuList = data.skuList
                    // .join('-')

                } else {
                    this.$message.error(data.errMsg || '失败');
                }

            })
        },
        jian() {
            if (this.editProduct.detailTabs.length > 1) {
                this.editProduct.detailTabs.pop();
            }
        },
        zeng() {
            this.editProduct.detailTabs.push({
                tabDetails: "",
                title: ""
            })
        },
        // 获取当前产品SKU
        // getSku() {
        //     console.log('------------------------------')
        //     axios({
        //         url: "/api-admin/productSku/getSkusByProductId/" + this.currentSkuData.productId,
        //         method: "get"
        //     }).then(result => {
        //         if (result.code == 0) {
        //             const { data } = result;
        //             this.productSkuList = data || []
        //         }
        //     })
        // },
        // 获取当前选中sku相应数据
        initSkuData(speciaId) {
            console.log('>>>>>>>>>>>>>>>>>>>11111111111111111111111111', JSON.parse(this.currentSkuData.productId))
            if (this.currentSkuData.productId) {
                let data = {
                    productId: JSON.parse(this.currentSkuData.productId),
                    speciaId: speciaId,
                }
                this.loading = true
                axios({
                    url: "/admin/productSku/listBySpeciaId",
                    method: "post",
                    data,
                }).then(result => {
                    if (result.code == 0) {
                        const { data } = result;
                        this.currentSkuData = data[0]
                    }
                    this.loading = false
                }).catch(err => {
                    this.loading = false
                })
            }

        },
        // 删除SKU
        deleteUser(index, id) {
            this.$confirm('确定要删除当前用户？', '提示', {
                type: 'warning'
            }).then(() => {
                this.productSkuList.splice(index, 1)

            }).catch(() => {
            })
        },
        // 保存sku
        saveCurrentSku() {
            if (this.selectArr.length == 0) {
                return this.$message.warning('请点击选择规格');
            }
            let key = this.selectArr.join('-')
            let arr = []
            this.currentSkuData.speciaId = key

            this.skuList.forEach((ele, index) => {
                console.log('>>>>>>>>>>>>>ele', ele)
                arr.push({ name: ele.name, value: ele.values[this.selectArr[index]] })
            });
            this.currentSkuData.spDataList = arr
            this.currentSkuData.price = parseInt(this.currentSkuData.priceDouble) * 100
            this.currentSkuData.originalPrice = parseInt(this.currentSkuData.priceDouble) * 100
            // 无当前SKU indexes则返回-1
            let hasCurrentKey = this.productSkuList.findIndex((ele, index) => ele.speciaId == key)
            if (hasCurrentKey == -1) {
                this.productSkuList.push(this.currentSkuData);
            } else {
                this.productSkuList[hasCurrentKey] = this.currentSkuData
            }
            console.log('>>>>>>>>>>>>>>>>>>>>>>', this.productSkuList.length, this.productSkuList)
        },
        // 删除SKU
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                axios({
                    url: "/api-admin/productSku/" + row.id,
                    method: "delete"
                }).then(result => {
                    this.$message.success(result.errMsg);
                    if (result.code == 0) {
                        this.biandong.splice(index, 1);
                    }
                })

            }).catch(() => { });
        },
        // 添加规格
        addSpecifications() {
            console.log('>>>>>>>>>>>>>>>>>>>>>>>', this.specificationsList)
            this.specificationsList.push({ name: "", unit: '', values: [''] })
            this.productSkuList = []
            // this.$forceUpdate()
        },

        // 保存规格
        saveSpecifications() {
            this.skuList = JSON.parse(JSON.stringify(this.specificationsList))
            let speciaId = []
            this.skuList.forEach(ele => {
                speciaId.push(0)
            });
            this.selectArr = speciaId
        },
        // 删除规格
        deleteSpecificationsItem(item, index) {
            this.$confirm('确定要删除此规格吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.specificationsList.splice(index, 1)
                    this.productSkuList = []
                    // this.$forceUpdate()
                })
                .catch(() => { });

        },
        // 添加规格值
        addSpecificationsValue(values) {
            values.push('')
        },
        // 删除规格值
        deleteSpecificationsValue(values, index1) {
            this.$confirm('确定要删除此规格值吗？', '提示', {
                type: 'warning'
            }).then(() => {
                values.splice(index1, 1)
            }).catch(() => { });
        },
        // 改变sku相应规格值
        changeSpecification(index, index1) {
            this.$set(this.selectArr, index, index1)
        },
        // 下一步
        nextStep() {
            if (this.stepIndex < 2) this.stepIndex++
        },
        // 上一步
        previousStep() {
            if (this.stepIndex > 1) this.stepIndex--
        },
        // 完成
        saveEdit() {

            this.editProduct.productSpecialVos = this.specificationsList
            let arr = []
            this.carouselimg.forEach(ele => {
                arr.push(ele.url)
            })
            this.editProduct.albumPics = arr.join(',')
            this.editProduct.skuList = this.productSkuList
            if (this.editProduct.skuList.length == 0) {
                return this.$message.warning('请至少添加一条SKU')
            }
            let url = '/admin/product/save'

            // console.log('>>>>>>>>>>>>>>>>>', JSON.stringify(this.editProduct))
            axios({
                url: url,
                method: "post",
                data: this.editProduct,
            }).then(result => {
                if (result.code == 0) {
                    this.editProduct.id = result.data
                    this.productSkuList.forEach(ele => {
                        ele.productId = result.data
                    });
                    this.$confirm(result.errMsg || '保存成功', '提示', {
                        type: 'success'
                    }).then(() => {
                        return this.$router.go(-1)
                    })
                } else {
                    // this.$confirm(result.errMsg || '保存失败', '提示', {
                    //     type: 'error'
                    // }).then(() => {
                    // })
                }
            })

        },
        // handleChange(value) {
        //     let selectObj = this.productCategoryList.find(item =>
        //         item.id == value
        //     )
        //     this.editProduct.categoryId = selectObj.id
        //     this.editProduct.categoryName = selectObj.name
        // },
        handleChange(value) {
            this.editProduct.categoryId = value[value.length - 1]
            // this.editProduct.categoryIds = value.join(',')
            this.editProduct.categoryName = this.$refs.myCascader.getCheckedNodes()[0].pathLabels[this.$refs.myCascader.getCheckedNodes()[0].pathLabels.length - 1]
            console.log('>>>>>>>>>>>>>>>>>', this.editProduct.categoryId, this.editProduct.categoryName)
        },
        handleUploadSuccess2(res) {
            this.editProduct.pic = res.data[0].url
            this.$forceUpdate()
        },
        handleUploadSuccess3(res, prams) {
            this.currentSkuData[prams] = res.data[0].url
            // this.$forceUpdate()
            console.log('----------------------------------', this.currentSkuData[prams])
        },
        uploadHttp({ file }) {
            this.$ossClient.ossPut(file).then(res => {
                console.log("文本进入这里")
                console.log("resresresres", res)
                // 获取富文本组件实例
                let quill = this.$refs.QuillEditor[this.currentEditorIndex].quill;
                // 如果上传成功
                if (res) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片，res为服务器返回的图片链接地址
                    quill.insertEmbed(length, 'image', res.requestUrls[0])
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                } else {
                    // 提示信息，需引入Message
                    Message.error('图片插入失败')
                }
            })
        },

        uploadHttp2({ file }) {
            let _this = this;
            this.$ossClient.ossPut(file).then(res => {
                console.log("jin2222 ")
                _this.editProduct.pic = res.requestUrls[0]
                console.log("--------------------this.editProduct.pic", this.editProduct.pic)
            })
        },
        uploadHttp3({ file }) {
            console.log("上传轮播再这里", file)
            this.$ossClient.ossPut(file).then(res => {
                this.carouselimg.push({ url: res.requestUrls[0] })
            })
        },
        uploadHttp4(file, item) {
            let _this = this;
            console.log('>>>>>>>>>>>>>>>file, item', file, item)
            this.$ossClient.ossPut(file).then(res => {
                console.log("resres图片", res)
                // item.pic = res.requestUrls[0]
                this.$set(item, 'pic', res.requestUrls[0])
            })
        },
        onError(err) {
            console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>err', err)
        },
        uploadVideoProcess(event, file, fileList) {
            this.videoFlag = true;
            this.videoUploadPercent = parseInt(file.percentage.toFixed(0));
        },
        uploadHttpVideo({ file }) {
            console.log("上传视频在这里---------", file)
            this.$ossClient.ossPut(file).then(res => {
                this.videoFlag = false
                this.editProduct.mainVideo = res.requestUrls[0]
            })
        },
        handleUploadVideoSuccess(res) {
            this.videoFlag = false
            this.editProduct.mainVideo = res.data[0].url
        },
        handleVideoPreview() {
            this.mainVideoVisible = true
        },
        // handleUploadSuccess(res) {
        //     console.log("文本进入这里")
        //     console.log("resresresres", res)
        //     // 获取富文本组件实例
        //     let quill = this.$refs.QuillEditor[this.currentEditorIndex].quill;
        //     // 如果上传成功
        //     if (res) {
        //         // 获取光标所在位置
        //         let length = quill.getSelection().index;
        //         // 插入图片，res为服务器返回的图片链接地址
        //         quill.insertEmbed(length, 'image', res.data[0].url)
        //         // 调整光标到最后
        //         quill.setSelection(length + 1)
        //     } else {
        //         // 提示信息，需引入Message
        //         Message.error('图片插入失败')
        //     }
        // },
        //删除轮播图
        handleRemove(file, fileList) {
            console.log('>>>>>>>>>>>>>>>>>>>>>', file, this.carouselimg,)
            let index = this.carouselimg.findIndex((ele, index) => ele.uid == file.uid)
            // let arr = []
            // fileList.forEach(ele => {
            //     if (ele.status == 'success') {
            //         arr.push({ url: ele.url })
            //     }
            // });
            this.carouselimg.splice(index, 1)
            // this.$forceUpdate()
            // var _this = this;
            // let str = "";
            // for (var i = 0; i < fileList.length; i++) {
            //     if (!fileList[i].response) {
            //         str += fileList[i].url + ","
            //     } else {
            //         str += fileList[i].response.data[0].url + ","
            //     }
            // }
            // if (str.length > 0) { str = str.substr(0, str.length - 1); }
            // _this.editProduct.albumPics = str;

        },
        //上传轮播图
        // fz(response, file, fileList) {
        //     var _this = this;
        //     let str = "";
        //     for (var i = 0; i < fileList.length; i++) {
        //         if (!fileList[i].response) {
        //             str += fileList[i].url + ","
        //         } else {
        //             str += fileList[i].response.data[0].url + ","
        //         }
        //     }
        //     if (str.length > 0) { str = str.substr(0, str.length - 1); }

        //     _this.editProduct.albumPics = str;

        // },
        // 上传遮罩
        zzUpload(event, file, fileList) {
            Loading.service(this.loaddingTip);
            if (event.percent == 100) {
                setTimeout(function () {
                    Loading.service(this.loaddingTip).close()
                }, 1000);
            }
        },
        // 预览轮播图片
        handlePictureCardPreview(file) {
            console.log("file", file)
            this.largeImg = file.url;
            this.carouselVisible = true;
        },
    }
}
</script>
<style lang="scss" scoped>
.margin-bottom-50 {
    margin-bottom: 50px;
}
.steps {
    width: 100%;
    margin-top: 17px;
    zoom: 1;
    color: #333;
    font-size: 14px;
}
.steps::after {
    content: '.';
    display: block;
    clear: both;
    visibility: hidden;
    font-size: 0;
    height: 0;
    line-height: 0;
}
.step {
    width: 220px;
    height: 40px;
    background: #dcdfe6;
    position: relative;
    .step_b {
        line-height: 40px;
        text-align: center;
    }
}
//旋转的小方形盒子
.rotateBox {
    content: '';
    border: 20px solid #fff;
    border-bottom: none;
    border-left: none;
    background-color: #dcdfe6;
    height: 36px;
    width: 36px;
    position: absolute;
    display: block;
    top: -7px;
    right: 30px;
    z-index: 10;
    transform: rotate(45deg);
}
.step_l {
    margin-right: 0;
}
.active {
    background: #1b93f8 !important;
    color: #fff;
}
//被激活的步骤条的样式
.active .rotateBox {
    color: #fff;
    background-color: #1b93f8;
    content: '';
    border: 20px solid #fff;
    border-bottom: none;
    border-left: none;
    height: 36px;
    width: 36px;
    position: absolute;
    display: block;
    top: -7px;
    right: 30px;
    z-index: 10;
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
    // -ms-transform:rotate(45deg);  /* IE 9 */
    // -moz-transform:rotate(45deg);   /* Firefox */
    // -webkit-transform:rotate(45deg); /* Safari 和 Chrome */
    // -o-transform:rotate(45deg);   /* Opera */
}
//最后一步取消向右箭头
.step:last-child .rotateBox {
    content: '';
    border: none;
    height: 0;
    width: 0;
    z-index: 11;
}
.container_title {
    color: #333;
    -webkit-text-stroke: 0.2px;
    font-size: 14px;
    margin-bottom: 15px;
}

.product-type {
    position: relative;
    width: 168px;
    padding: 5px;
    border: 1px solid #1b93f8;
    border-radius: 4px;
    .product-type-img {
        width: 64px;
        height: 64px;
        border-radius: 4px;
    }
    .product-select {
        position: absolute;
        width: 16px;
        height: 16px;
        right: -6px;
        bottom: -6px;
    }
}
/deep/.el-upload-list--picture-card .el-upload-list__item {
    width: 80px !important;
    height: 80px !important;
}
/deep/.el-upload--picture-card {
    width: 80px !important;
    height: 80px !important;
    line-height: 80px !important;
}
::v-deep {
    .avatar-uploader {
        width: 80px;
        height: 80px;
        .el-upload {
            width: 80px;
            height: 80px;
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .el-upload:hover {
            border-color: #409eff;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 80px;
            height: 80px;
            line-height: 80px;
            text-align: center;
        }
    }
    .avatar {
        width: 80px;
        height: 80px;
        display: block;
    }
    .video-uploader {
        width: 256px;
        height: 180px;
        .el-upload {
            width: 256px;
            height: 180px;
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .el-upload:hover {
            border-color: #409eff;
        }
        .video-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 256px;
            height: 180px;
            line-height: 180px;
            text-align: center;
        }
        .video {
            width: 256px;
            height: 180px;
            display: block;
        }
    }
}
.t-td {
    padding: 5px 0;
    .el-input,
    .el-select {
        width: 80%;
    }
}
.specifications-box {
    margin-bottom: 20px;
}
.specifications-item {
    position: relative;
    background: #f5f5f5;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 15px;
    margin-top: 15px;
    .el-icon-error {
        position: absolute;
        right: -6px;
        top: -6px;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.5);
    }
}
.specifications-value {
    .input-box {
        position: relative;
        width: 25%;
        margin-bottom: 15px;
        margin-right: 15px;
        .el-icon-error {
            position: absolute;
            right: -6px;
            top: -4px;
            color: rgba(0, 0, 0, 0.5);
        }
    }
    .add_btn {
        margin-bottom: 15px;
        margin-left: 15px;
    }
}
.sku-box {
    .specifications-value-box {
        margin-bottom: 20px;
        .specifications-title {
            color: #333;
            -webkit-text-stroke: 0.2px;
            font-size: 14px;
        }
        .specifications-value {
            text-align: center;
            min-width: 50px;
            padding: 2px 4px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            color: #999;
            margin-right: 20px;
            margin-top: 10px;
            &.active {
                color: #fff;
                border: 1px solid #1b93f8;
                background: #1b93f8;
            }
        }
    }
    .specifications-value-box + .specifications-value-box {
        margin-top: 10px;
    }
}
.footer_box {
    text-align: center;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    box-sizing: border-box;
}
.my-switchStyle {
    margin-right: 25px;
}
.my-switchStyle {
    ::v-deep {
        .el-switch__label {
            position: absolute;
            display: none;
            color: #fff;
        }
        .el-switch__label--left {
            z-index: 9;
            left: 6px;
        }
        .el-switch__label--right {
            z-index: 9;
            left: -16px;
        }
        .el-switch__label.is-active {
            display: block;
        }
        .el-switch__label * {
            font-size: 12px;
        }
        .el-switch__core,
        .el-switch__label {
            width: 52px !important;
        }
    }
}
.tips {
    text-align: right;
    color: #f56c6c;
    font-size: 14px;
}
</style>